extends TileMap

## 游戏地图
class_name LevelMap

## 被删除的对象
var deleted_objs : Array = []
## 子节点数据
var objs_data : Dictionary = {}
## 路径规划类
var astar: AStarGrid2D

## 保存数据
func get_data() -> Dictionary:
	return {
		"deleted_objs": deleted_objs,
		"objs_data": _get_children_objs_data()
	}

## 还原数据
func set_data(data: Dictionary):
	self.deleted_objs = data["deleted_objs"]
	self.objs_data = data["objs_data"]

## 获取路径规划数据
func get_route_path(start: Vector2, end: Vector2) -> Array:
	var start_local = self.local_to_map(self.to_local(start))
	var end_local = self.local_to_map(self.to_local(end))
	var result = []
	for path in self.astar.get_id_path(start_local, end_local):
		result.append(to_global(self.map_to_local(path)))
	return result

func _ready():
	self._init_astar()
	self.connect("child_exiting_tree", _on_child_exiting_tree.bind())
	self.connect("child_entered_tree", _on_child_entered_tree.bind())

## 初始化路径规划算法
func _init_astar():
	self.astar = AStarGrid2D.new()
	self.astar.diagonal_mode = AStarGrid2D.DIAGONAL_MODE_NEVER
	self.astar.region = Rect2i(0, 0, 13, 13)
	self.astar.cell_size = Vector2(16, 16)
	self.astar.update()
	for cell in self.get_used_cells(0):
		self.astar.set_point_solid(cell)

## 获取子节点数据
func _get_children_objs_data():
	for child in get_children():
		if child.has_method("get_data"):
			objs_data[str(child.position)] = child.call("get_data")
	return objs_data
	
## 玩家触碰
func _on_player_collide(player: Player):
	return false

## 节点移除回调
func _on_child_exiting_tree(node: Node2D):
	## 被删除物品记录
	var path = [node.position.x,node.position.y]
	deleted_objs.push_front(path)

## 节点添加回调
func _on_child_entered_tree(node: Node2D):
	# 节点数据还原
	if self.objs_data.has(str(node.position)) and node.has_method("set_data"):
		node.call("set_data", self.objs_data[str(node.position)])
	# 已经被删除的物品直接移除
	var path = [node.position.x,node.position.y]
	if self.deleted_objs.has(path):
		node.queue_free()
